//
//  BDDetailLoginViewController.m
//  BadBoy
//
//  Created by 余勇 on 2017/3/10.
//  Copyright © 2017年 com.8xiong. All rights reserved.
//

#import "BDDetailLoginViewController.h"
#import "BDDetailLoginTableViewCell.h"
#import "CameraPhotoBehavior.h"
#import "BDUserModel.h"
#import "BDMD5.h"

@interface BDDetailLoginViewController ()<UITableViewDelegate, UITableViewDataSource>
{
    BOOL waitCityList;
    
}
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSArray *datasource;

@property (nonatomic, strong) NSString *avatarIma;
@property (nonatomic, strong) NSString *inviteString;
@property (nonatomic, strong) UIView *customView;
@end

@implementation BDDetailLoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor colorWithRed:247/255.0 green:247/255.0 blue:247/255.0 alpha:1.0f];
    
    self.title = ASLocalizedString(@"更新资料");
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self setCurrentDatasource];
    
    [self.tableView reloadData];
    
    self.customView = [[UIView alloc] init];
    _customView.left = 0;
    _customView.size = CGSizeMake(self.view.width, 80);
    _customView.bottom = self.view.bottom;
    [self.view addSubview:_customView];
    
    UIButton *loginButton = [UIButton buttonWithType:UIButtonTypeCustom];
    loginButton.size = CGSizeMake(_customView.width - 20, 40);
    loginButton.center = CGPointMake(_customView.width / 2.0, _customView.height / 2.0);
    [loginButton setTitle:ASLocalizedString(@"确定")forState:UIControlStateNormal];
    [loginButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    loginButton.backgroundColor = kLoginButtonColor;
    loginButton.titleLabel.font = [UIFont systemFontOfSize:17];
    loginButton.layer.masksToBounds = YES;
    loginButton.layer.cornerRadius = 6;
    [_customView addSubview:loginButton];
    [[loginButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        // BDLog(ASLocalizedString(@"点击了确定"));
        [self.view resignFirstResponder];
        NSString *alert = nil;
        if (self.phone.length != 11) {
            alert = ASLocalizedString(@"请填写合法的手机号");
        }
        else if (self.nickName.length == 0) {
            alert = ASLocalizedString(@"请填写昵称");
        }else if ([self chineseCountOfString:self.nickName] <= 0 || [self chineseCountOfString:self.nickName] > 16) {
            alert = ASLocalizedString(@"昵称长度不符，请重新填写");
        }else if (self.code.length == 0) {
            alert = ASLocalizedString(@"请填写验证码");
        }else if (self.code.length != 4) {
            alert = ASLocalizedString(@"验证码错误，请重新填写");
        }
        if (alert != nil) {
            [MBManager showCustomView:[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"error"]] title:alert clickHidden:NO clickBlock:nil];
            return;
        }
        if (self.registType == BDRegistTypeNoRegist) {
            //调用注册接口
            [self registNewUser];
        }else{
            //调用修改接口，然后登录
            [self exchangeNickname];
        }
    }];
    
//    [[[NSNotificationCenter defaultCenter] rac_addObserverForName:@"haveCityList" object:nil] subscribeNext:^(NSNotification * _Nullable x) {
//        if (waitCityList == YES) {
//            waitCityList = NO;
//            [MBManager hideAlert];
//            [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATION_LOGINCHANGE object:@YES];
//        }
//    }];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    
}

- (void)setCurrentDatasource{
//    @{@"title":ASLocalizedString(@"头像"), @"image":self.avatarIma ? self.avatarIma : @"avatar", @"first":@YES},
    if (self.registType ==BDRegistTypeNoNickname) {
        self.datasource = @[
                            @{@"title":ASLocalizedString(@"昵称"), @"subTitle":self.nickName ? self.nickName : @""},@{@"title":ASLocalizedString(@"邀请码"),@"textField":@YES,@"last":@YES}];
    }else {
        if (self.editType == BDEditTypeThird) {
            self.datasource = @[
                                @{@"title":ASLocalizedString(@"昵称"), @"subTitle":self.nickName ? self.nickName : @""},
                                @{@"title":ASLocalizedString(@"手机号码"), @"getCode":@YES},
                                @{@"title":ASLocalizedString(@"验证码"), @"textField":@YES},@{@"title":ASLocalizedString(@"邀请码"),@"textField":@YES,@"last":@YES}];
        }else{
    //        @{@"title":ASLocalizedString(@"头像"), @"image":@"avatar", @"first":@YES},
            self.datasource = @[
                                @{@"title":ASLocalizedString(@"昵称"), @"subTitle":self.nickName ? self.nickName : @""},@{@"title":ASLocalizedString(@"邀请码"),@"textField":@YES,@"last":@YES}];
        }
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.datasource.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 45;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    BDDetailLoginTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (cell == nil) {
        cell = [[BDDetailLoginTableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"cell"];
    }
    [cell configeWithDic:self.datasource[indexPath.row] editBlock:^(NSString *str) {
        if (self.editType == BDEditTypeThird){
            if (indexPath.row == 0) {
                self.nickName = str;
            }else if (indexPath.row == 1) {
                self.phone = str;
            }else if (indexPath.row == 2) {
                self.code = str;
            }else{
                self.inviteString = str;
            }
        }else{
            if (indexPath.row == 0) {
                self.nickName = str;
            }else{
                self.inviteString = str;
            }
        }
        
    }];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    /*
    if (indexPath.row == 0) {
        [[CameraPhotoBehavior behavior] getPhotoWithtargetVC:self FinishBlock:^(UIImage *image) {
            NSString *newAvatarPath = [CachePaths stringByAppendingPathComponent:@"newAvatar.jpg"];
            if ([UIImageJPEGRepresentation(image, 1) writeToFile:newAvatarPath atomically:YES]) {
                self.avatarIma = newAvatarPath;
                [self setCurrentDatasource];
                [self.tableView reloadData];
            }
        }];
    }
    */
}

- (UITableView *)tableView{
    if (!_tableView) {
        self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, kBDTopHeight, kBDScreenWidth, kBDScreenHeight - kBDTopHeight) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.tableFooterView = [self customTableViewFootView];
        _tableView.scrollEnabled = NO;
        UIView *header = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, 12.5)];
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.tableHeaderView = header;
        _tableView.bounces = NO;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction)];
        [_tableView addGestureRecognizer:tap];
        [self.view addSubview:_tableView];
    }
    return _tableView;
}
-(void)tapAction{
    [self.view endEditing:YES];
}

- (UIView *)customTableViewFootView{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, 80)];
    UILabel *label = [[UILabel alloc] init];
    label.left = 10;
    label.top = 10;
    label.font = [UIFont systemFontOfSize:12];
    label.textColor = [UIColor redColor];
    label.width = kBDScreenWidth - 20;
    label.numberOfLines = 0;
    label.text = ASLocalizedString(@"注意：\n1.每个新用户只有一次填写邀请码的机会，注意填写您的邀请码。\n2.填写正确的邀请码您将获得10元余额的奖励，余额可用于购买主题、商城消费，也可直接提现。");
    label.height = [label.text heightForFont:[UIFont systemFontOfSize:12] width:label.width];
    [view addSubview:label];
    
    return view;
}

- (BOOL)isChinesecharacter:(NSString *)string{
    if (string.length == 0) {
        return NO;
    }
    unichar c = [string characterAtIndex:0];
    if (c >=0x4E00 && c <=0x9FA5) {
        return YES;//汉字
    }else{
        return NO;//英文
    }
}

//计算文本中字符的个数
- (NSInteger)chineseCountOfString:(NSString *)string{
    int ChineseCount = 0;
    int characterCount = 0;
    if (string.length == 0) {
        return 0;
    }
    for (int i = 0; i<string.length; i++) {
        unichar c = [string characterAtIndex:i];
        if (c >=0x4E00 && c <=0x9FA5){
            ChineseCount++ ;//汉字
        }else{
            characterCount++;//英文
        }
    }
    return ChineseCount * 2 + characterCount;
}

- (void)registNewUser{
    NSDictionary *para = nil;
    if (self.editType == BDEditTypeThird) {
        para = @{@"open_id":self.openid,
                 @"access_token":self.access_token,
                 @"nickname":self.nickName,
                 @"mobile":self.phone,
                 @"code":self.code};
    }else{
        para = @{@"nickname":self.nickName,
                 @"mobile":self.phone,
                 @"code":self.code};
    }
    [MBManager showLoadingAlert:nil clickHidden:NO clickBlock:nil];
    [BDUserModel registWithPara:para.mutableCopy completionHandler:^(id obj, NSError *error) {
        if (error == nil) {
            [self verifyTheInvitation];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"updateUnreadCount" object:nil];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"getConvitasionFromDB" object:nil];
            [self.navigationController dismissViewControllerAnimated:YES completion:nil];
        }else{
            NSString *alert = ASLocalizedString(@"修改失败，请稍后再试");
            if (error.code == 40002) {
                alert = ASLocalizedString(@"验证码错误或失效");
            }else if (error.code == 10007) {
                alert = ASLocalizedString(@"该手机号已被注册，请直接登录");
            }else if (error.code == 10004) {
                alert = ASLocalizedString(@"昵称已存在，请更换昵称");
            }
            [MBManager showCustomView:[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"error"]] title:alert clickHidden:NO clickBlock:nil];
        }
    }];
}

-(void)verifyTheInvitation{
    
    NSString *url = [NSString stringWithFormat:@"%@invite/%@",KBDBaseURL,self.inviteString];
    RACSignal *signal = [[BDNetworkingServer yy_POST:url parameters:nil validation:[BDUserModel getHeaderValidation] automaticProcessingError:YES] execute:nil];
    [signal subscribeNext:^(id  _Nullable x) {
        [MBManager showBriefAlert:ASLocalizedString(@"恭喜你，已经获得10元余额的奖励")clickHidden:NO clickBlock:nil];
    }];
    
    [signal subscribeError:^(NSError * _Nullable error) {
        switch (error.code) {
            case 40001:
                [MBManager showBriefAlert:ASLocalizedString(@"邀请码填写错误")clickHidden:NO clickBlock:nil];
                break;
                
            default:
                break;
        }
    }];
}

- (void)exchangeNickname{
    //如果是被注册过的，那么不需要再验证手机号的，只需要输入昵称，修改成功就可以了，所以需要在前一个页面分开
    //情况的优先级应该是：是否注册过，如果没有注册过，那么就区别当前注册类型，如果已经注册过，那么就是nickname是否存在
    //修改成功之后需要登录环信，获取好友列表
    NSDictionary *para = nil;
    if (self.editType == BDEditTypeThird) {
        para = @{@"open_id":self.openid,
                 @"access_token":self.access_token,
                 @"nickname":self.nickName};
    }else{
        para = @{@"nickname":self.nickName,
                 @"mobile":self.phone,
                 @"code":self.code};
    }
    [MBManager showLoadingAlert:ASLocalizedString(@"正在登陆")clickHidden:NO clickBlock:nil];
    [BDUserModel completionInfoWithPara:para.mutableCopy completionHandler:^(id obj, NSError *error) {
        if (error == nil) {
            [MBManager hideAlert];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"updateUnreadCount" object:nil];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"getConvitasionFromDB" object:nil];
            [self.navigationController dismissViewControllerAnimated:YES completion:nil];
        }else{
            NSString *alert = ASLocalizedString(@"修改失败，请稍后再试");
            if (error.code == 40002) {
                alert = ASLocalizedString(@"验证码错误或失效");
            }else if (error.code == 10004) {
                alert = ASLocalizedString(@"昵称已存在，请更换昵称");
            }
            [MBManager showCustomView:[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"error"]] title:alert clickHidden:NO clickBlock:nil];
        }
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
